
#include <pthread.h>
#include<iostream>
#include<vector>
#include<unistd.h>
using namespace std;
int cnt=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//全局的条件变量变量
//同步
void *Count(void *args){
    pthread_detach(pthread_self());//分离主线程和子线程
    uint64_t number=(uint64_t)args;
    cout<<"phread"<<number<<"  create success"<<endl;
    while(true){
        pthread_mutex_lock(&mutex);//上锁
        pthread_cond_wait(&cond,&mutex);//休眠并进入队列，并释放锁
        //为什么进入休眠，因为临界资源没有进入状态
        //临界资源就不就绪要看临界资源的状态，需要判断，而判断本身就是临界资源，所以要在锁的里面
        cout<<"pthread:"<<number<<", cnt:"<<cnt++<<endl;
        pthread_mutex_unlock(&mutex);        
    }
}
int main()
{
    for(uint64_t i=0;i<5;i++){
        pthread_t tid;
        pthread_create(&tid,NULL,Count,(void*)i);
        usleep(1000);
    }
    sleep(3);
    cout<<"main thread ctrl begin"<<endl;
    while(true){
       // pthread_cond_signal(&cond);//唤醒
        pthread_cond_broadcast(&cond);
        cout<<"signal one thread"<<endl;
        sleep(1);
    }
    return 0;
}